package me.sauce.folkpocket48.home.refresh

import android.arch.lifecycle.ViewModelProviders
import android.content.ComponentName
import android.content.Context.BIND_AUTO_CREATE
import android.content.Intent
import android.content.ServiceConnection
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.orhanobut.logger.Logger
import me.sauce.folkpocket48.IMyAidlInterface
import me.sauce.folkpocket48.R
import me.sauce.folkpocket48.SCallback
import me.sauce.folkpocket48.ViewModelFactory
import me.sauce.folkpocket48.base.BaseFragment
import me.sauce.folkpocket48.databinding.ActivityRefreshBinding
import me.sauce.folkpocket48.home.sample.TestActivity
import me.sauce.folkpocket48.service.SimpleService

/**
 * @author sauceWu
 * @since 2018/1/2 18:40
 */

class RefreshFragment : BaseFragment() {

    companion object {
        fun newInstance() = RefreshFragment()
    }

    lateinit var db: ActivityRefreshBinding
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        db = DataBindingUtil.inflate<ActivityRefreshBinding>(inflater, R.layout.activity_refresh, container, false).apply {
            vm = ViewModelProviders.of(this@RefreshFragment, ViewModelFactory.getInstance(activity!!.application)).get(RefreshViewModule::class.java)
        }
        return db.root

    }

    lateinit var mService: IMyAidlInterface
    var sCallback = object : SCallback.Stub() {
        override fun onUpdate(i: Long) {
            db.vm?.time?.set(i.toString())
        }
    }


    var connect = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Logger.d(name)
            mService = IMyAidlInterface.Stub.asInterface(service)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Logger.d(name)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Logger.w("okfffffffff")



        db.bt123.setOnClickListener {
            //            db.vm?.dataLoading?.set(false)
//            db.vm?.time?.set("haha")
//            val message = Message()
//            message.what = SimpleService.MSG_SAY_HELLO
//            mService.basicTypes(1, 1, true, 1f, 1.00, "1")
//            mService.registCallBack(sCallback)
//
            TestActivity.start(activity)
        }
        val intent = Intent()
        intent.setClass(activity, SimpleService::class.java)
        activity!!.bindService(intent, connect, BIND_AUTO_CREATE)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        activity?.unbindService(connect)
    }

}
